package com.es.disped.service.wechat;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.es.disped.api.wechat.WeChatService;
import com.es.disped.common.constant.WeChat;
import com.es.disped.common.model.MsgModel;
import com.es.disped.common.wechat.http.config.WeChatConfig;
import com.es.disped.common.wechat.http.request.AccessRequest;
import com.es.disped.common.wechat.http.response.AccessResponse;
import com.es.disped.common.wechat.http.response.TemplateMsgResponse;
import com.es.disped.common.wechat.model.TemplateMsg;
import com.es.disped.service.http.HttpServiceImpl;

@Service("weChatService")
public class WeChatServiceImpl extends HttpServiceImpl implements WeChatService {
	
	@Override
	public MsgModel getAccessToken() {
        AccessRequest request = new AccessRequest(WeChatConfig.getAppId(), WeChatConfig.getAppsecret());
        // 构建请求参数
        Map<String, String> map = new HashMap<String, String>();
        map.put("grant_type", request.getGrant_type());
        map.put("appid", request.getAppid()); 
        map.put("secret", request.getSecret());
        String result = this.doGet(WeChat.getAccessTokenUrl(), map);
        AccessResponse response = JSONObject.parseObject(result, AccessResponse.class);
        return new MsgModel(response!=null?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),response);
	}

	@Override
	public MsgModel sendTemplateMessage(Map<String, Object> paramMap, String templateId, String toUser, String accessToken) {
		TreeMap<String, TreeMap<String,String>> params = new TreeMap<String,TreeMap<String,String>>();
        //模板参数组装
		for(Entry<String, Object> entry:paramMap.entrySet())
		{
			params.put(entry.getKey(), TemplateMsg.item(entry.getValue().toString(), "#000000"));
		}
        TemplateMsg templateMsg = new TemplateMsg();
        templateMsg.setTemplate_id(templateId);
        templateMsg.setTouser(toUser);
        templateMsg.setUrl(WeChat.getTemplateMessageDetailUrl());
        templateMsg.setData(params);
		String url=WeChat.getTemplateMessageUrl(accessToken);
		String data=JSONObject.toJSONString(templateMsg);
		String result=this.postJson(url, data);
		TemplateMsgResponse response=JSONObject.parseObject(result, TemplateMsgResponse.class);
		return new MsgModel(response!=null?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(), response);
	}

	
}
